<!-- src/view/department.vue -->
<template>
  <div class="department-container">
    <h1>部门管理</h1>

    <!-- 查询部门 -->
    <el-card class="search-card">
      <el-form :model="searchDept" label-width="80px" inline>
        <el-form-item label="部门名称">
          <el-input v-model="searchDept.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="searchDept.description" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadDepartments">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 新增部门 -->
    <div class="toolbar">
      <el-button type="primary" @click="openAddDialog">新增部门</el-button>
    </div>

    <!-- 部门表格 -->
    <el-table
        :data="pagedData"
        border
        style="width: 100%"
        v-loading="loading"
        element-loading-text="数据加载中..."
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="部门名称" width="200" />
      <el-table-column prop="description" label="描述" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteDepartment(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-if="departments.length > 0"
        background
        layout="prev, pager, next, sizes, total"
        :current-page="page"
        :page-size="pageSize"
        :page-sizes="[5, 10, 20]"
        :total="departments.length"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        style="margin-top: 20px; justify-content: center;"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="editForm.id ? '编辑部门' : '新增部门'"
        width="500px"
    >
      <el-form :model="editForm" label-width="100px" ref="deptForm">
        <el-form-item
            label="部门名称"
            prop="name"
            :rules="[{ required: true, message: '请输入部门名称', trigger: 'blur' }]"
        >
          <el-input v-model="editForm.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item
            label="描述"
            prop="description"
        >
          <el-input v-model="editForm.description" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import departmentApi from '../api/departmentapi.js';

// 数据状态
const departments = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const deptForm = ref(null);

// 分页参数
const page = ref(1);
const pageSize = ref(5);
const pagedData = computed(() => {
  const start = (page.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return departments.value.slice(start, end);
});

// 查询条件
const searchDept = reactive({
  name: '',
  description: ''
});

// 表单数据
const editForm = reactive({
  id: null,
  name: '',
  description: ''
});

// 加载部门列表
const loadDepartments = async () => {
  loading.value = true;
  try {
    const res = await departmentApi.list(searchDept);
    if (res && res.code === 200) {
      departments.value = Array.isArray(res.data) ? res.data : [];
    } else {
      departments.value = [];
      ElMessage.error(res?.msg || '数据加载失败');
    }
    page.value = 1;
  } catch (err) {
    console.error('加载部门列表失败:', err);
    departments.value = [];
    ElMessage.error('加载部门列表失败: ' + (err.message || '请检查网络连接'));
  } finally {
    loading.value = false;
  }
};

// 重置查询
const resetSearch = () => {
  searchDept.name = '';
  searchDept.description = '';
  loadDepartments();
};

// 分页事件处理
const handlePageChange = (newPage) => {
  page.value = newPage;
};
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  page.value = 1;
};

// 打开新增对话框
const openAddDialog = () => {
  Object.assign(editForm, { id: null, name: '', description: '' });
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (dept) => {
  Object.assign(editForm, dept);
  dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  try {
    if (!editForm.name) {
      ElMessage.warning('部门名称不能为空');
      return;
    }
    if (editForm.id) {
      const res = await departmentApi.edit(editForm);
      if (res && res.code === 200) {
        ElMessage.success('更新成功');
        dialogVisible.value = false;
        loadDepartments();
      } else {
        ElMessage.error(res?.msg || '更新失败');
      }
    } else {
      const res = await departmentApi.add(editForm);
      if (res && res.code === 200) {
        ElMessage.success('新增成功');
        dialogVisible.value = false;
        loadDepartments();
      } else {
        ElMessage.error(res?.msg || '新增失败');
      }
    }
  } catch (err) {
    console.error('操作失败:', err);
    ElMessage.error('操作失败: ' + (err.message || '请检查网络连接'));
  }
};

// 删除部门
const deleteDepartment = async (id) => {
  ElMessageBox.confirm(
      '确定要删除该部门吗？此操作不可恢复。',
      '删除确认',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
  ).then(async () => {
    try {
      const res = await departmentApi.del(id);
      if (res && res.code === 200) {
        ElMessage.success('删除成功');
        loadDepartments();
      } else {
        ElMessage.error(res?.msg || '删除失败');
      }
    } catch (err) {
      console.error('删除失败:', err);
      ElMessage.error('删除失败: ' + (err.message || '请检查网络连接'));
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

onMounted(() => {
  loadDepartments();
});
</script>

<style scoped>
.department-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
  text-align: right;
}
</style>
